package com.zxy.lm.controller;


import com.zxy.lm.VO.UserLoginVO;
import com.zxy.lm.VO.UserRegisterVO;
import com.zxy.lm.entity.User;
import com.zxy.lm.service.UserService;
import com.zxy.lm.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpSession;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author jiusi
 * @since 2021-06-22
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public String login(UserLoginVO userVO, HttpSession session, Model model) {
        User user = userService.login(userVO);
        if (null != user) {
            session.setAttribute("user", user);
            return "redirect:/main";
        } else {
            model.addAttribute("lmsg", "账号或密码错误");
            return "index";
        }
    }

    @PostMapping("/register")
    public String register(UserRegisterVO userVO, Model model) {
        //有没填写字符的信息，直接注册失败
        if (!StringUtils.allHasText(userVO.getUsername(), userVO.getPassword(), userVO.getEmail())){
            model.addAttribute("rmsg", "注册失败");
            return "register";
        }
        boolean b = userService.register(userVO);
        if (!b) {
            model.addAttribute("rmsg", "注册失败");
        }
        return "register";
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/";
    }

    @PostMapping("/changePassword")
    public String change(HttpSession session, Model model, String pass, String newPass, String vPass) {
        if (!newPass.equals(vPass)) {
            model.addAttribute("cmsg", "新密码与确认密码不符");
            return "redirect:/changePassword";
        }
        Object o = session.getAttribute("user");
        //验证是否登录
        if (!(o instanceof User)) {
            model.addAttribute("lmsg", "请先登录");
            return "index";
        }
        User user = (User) o;
        //修改密码
        boolean b = userService.changePassword(user.getUsername(), pass, newPass);
        if (!b) {
            model.addAttribute("cmsg", "修改密码失败，请检查信息");
            return "changePassword";
        }
        model.addAttribute("imsg", "修改成功");
        return "/info";
    }
}

